<template>
  <van-popup
      v-model:show="showMyplan"
      round
      position="top"
  >
    <div class="info-item" style="margin: 15px">
      <span class="key">测试项目:</span><div class="value">{{ myplanInfo }}</div>
  </div>
       </van-popup>

  <div class="title" ><span class="title-text">服务切换</span> <van-icon @click="pushReLoadPlan" class="replay-icon" name="replay" /></div>
  <nut-tabs v-model="tab1value" @click="changeClick" type="smile" size="large">
    <template #titles>
      <div class="nut-tabs__titles-item nut-tabs__titles-item-check" id="tabs1" @click="clickTab('tabs1', '0')" :key="0">
        <div class="tab-item"> 体测安排 </div>
      </div>
      <div class="nut-tabs__titles-item" id="tabs2" @click="clickTab('tabs2', '1')" :key="1">
        <div class="tab-item"> 我的预约 </div>
      </div>
    </template>

    <nut-tabpane pane-key="0">

      <div v-if="allPlan.length != 0">
        <div v-for="item in allPlan" >
          <div class="test-project" :style="{ 'backgroundImage': `url('${item.backSrc}')` }" @click="openCheckTest(item)">
            <div class="project-key1 project-item">
              <span class="item-desc">[{{ item.item }}]</span>
              <span class="people-num">&nbsp;{{ item.applys }}/{{ item.persons }}</span>
            </div>
            <div class="project-key2 project-item">{{ item.typeDesc}}</div>
            <div class="project-key31 project-item">
              <img src="../../image/project/calendar-todo.png" />{{ item.thedate.slice(5) }}日&nbsp;{{ item.thetime.slice(0,5) }}-{{ item.thetime.slice(11,16) }}
            </div>
            <div class="project-key3 project-item">
              <img src="../../image/project/path.png" />

              <span class="place-desc"> {{ item.placeDesc }}</span>

            </div>
          </div>
        </div>
      </div>
      <div v-if="allPlan.length == 0" class="empty-image-box">
        <img class="empty-image" src="../../image/testplan.png">
        <p class="empty-text">暂无测试安排</p>
      </div>

    </nut-tabpane>
    <nut-tabpane pane-key="1">
        <div class="user-detail">
          <div class="user-info">
            <img style="width: 50px;height: 50px;display: inline-block" src="/user_info.png">
            <span>{{ userInfo.name }}({{ userInfo.number }})</span>
          </div>
          <div class="user-info">
            <img style="width: 41px;height: 41px;padding: 4px;display: inline-block" src="/time_info.png">
            <span>{{ time.year }}-{{time.moth +1}}-{{time.day}}&nbsp;{{time.hour}}:{{time.min}}:{{time.second}}&nbsp;<span style="font-size: larger;color: #007aff">{{time.mill}}</span></span>
          </div>
        </div>
      <div v-if="myPlan.length != 0">
        <div v-for="item in myPlan" >
          <div class="test-project" :style="{ 'backgroundImage': `url('${item.backSrc}')` }" >
            <div class="project-key1 project-item">
              <span class="item-desc" @click="showMyplanInfo(item.item)">[{{ item.item }}]</span>
<!--              <span class="people-num">&nbsp;{{ item.applys }}/{{ item.persons }}</span>-->
              <span  class="people-reback" @click="rebackTest(item)">{{item.cx==1 ? '撤销': ''}}</span>
            </div>
            <div class="project-key2 project-item">{{ item.typeDesc}}</div>
            <div class="project-key31 project-item">
              <img src="../../image/project/calendar-todo.png" />{{ item.thedate.slice(5) }}日&nbsp;{{ item.thetime.slice(0,5) }}-{{ item.thetime.slice(11,16) }}
            </div>
            <div class="project-key3 project-item">
              <img src="../../image/project/path.png" />
              <span class="place-desc">{{ item.placeDesc }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="myPlan.length == 0" class="empty-image-box">
        <img class="empty-image" src="../../image/myplan.png">
        <p  class="empty-text">无预约项目</p>
      </div>
    </nut-tabpane>
  </nut-tabs>
  <nut-popup position="bottom" round :style="{ height: '400px' }" v-model:visible="showCheck">
    <!--    <nut-cell-group class="cell-box">-->
    <!--      <nut-cell size="large" title="链接" :desc="checkItem.key1"></nut-cell>-->
    <!--      <nut-cell size="large" title="URL 跳转" desc="https://m.jd.com" ></nut-cell>-->
    <!--      <nut-cell size="large" title="路由跳转"></nut-cell>-->
    <!--    </nut-cell-group>-->
    <div class="check-title">&nbsp;
      <nut-icon size="15px" name="tips" style="margin-top: 2px;margin-right: 5px" color="#cccccc" />
      <div>确认预约信息</div>
    </div>
    <nut-divider />
    <div class="cell-box">
      <div class="info-item"
        ><div class="key">测试项目:</div><div class="value">{{ checkItem.item }}</div>
      </div>
      <div class="divider-xian" />
      <div class="info-item"
        ><div class="key">测试日期:</div><div class="value">{{ checkItem.thedate }}</div>
      </div>
      <div class="divider-xian" />
      <div class="info-item"
        ><div class="key">测试时间:</div><div class="value">{{ checkItem.thetime }}</div>
      </div>
      <div class="divider-xian" />
      <div class="info-item"
        ><span class="key">测试类型:</span><div class="value">{{ checkItem.typeDesc }}</div>
      </div>
      <div class="divider-xian" />
      <div class="info-item"
        ><span class="key">测试地点:</span><div class="value">{{ checkItem.placeDesc }}</div>
      </div>
      <div class="divider-xian" />
      <div class="info-item"
        ><span class="key">剩余名额:</span><div class="value">{{ checkItem.persons - checkItem.applys }}人</div>
      </div>
      <div class="divider-xian" />
    </div>
    <div class="check-button">
      <nut-button type="default" @click="canelCheck()">取消</nut-button>
      <nut-button type="info" @click="confireCheck()">确认预约</nut-button>
    </div>
  </nut-popup>
</template>

<script>
  // import {reactive} from 'vue';

  // import {List} from "@varlet/ui";
  import { getOrderTest,getMyOrderTest,pushOrderTest } from "../../api/orderTest";
  import Toast from 'vant/lib/toast';
  import 'vant/es/toast/style';
  import {fail} from "vant/lib/toast/function-call";
  import { Notify } from 'vant';
  import 'vant/es/notify/style';
  import {useUserStore} from "../../store/modules/user";
  import {rebackFreeTest} from "../../api/getTest";
  import { Dialog } from 'vant';
  import 'vant/es/dialog/style';

  export default {
    name: '',
    setup() {
      const state = reactive({
        tab1value: '0',
      });
      return { state };
    },
    data() {
      return {
        tab1value: 0,
        allPlan: [
          {
            item: '裸眼视力',
            thedate: '09-10 14:00-16:00',
            type: '(体测)',
            place: '团结广场',
            applys: '660',
            persons: '1000',
            backSrc: './eyesight.png',
          },
          {
            item: '50米、800米、1000米',
            thedate: '09-10 14:00-16:00',
            type: '(不及格补测)',
            key4: '民族体育场',
            applys: '660',
            persons: '1000',
            backSrc: './run_test.png',
          },
        ],
        myPlan: [
          {
            item: '裸眼视力',
            thedate: '09-10 14:00-16:00',
            type: '(体测)',
            place: '团结广场',
            applys: '660',
            persons: '1000',
            backSrc: './eyesight.png',
          },
          {
            item: '50米、800米、1000米',
            thedate: '09-10 14:00-16:00',
            type: '(不及格补测)',
            key4: '民族体育场',
            applys: '660',
            persons: '1000',
            backSrc: './run_test.png',
          },
        ],
        showCheck: false,
        checkItem: {},
        throttle: null,
        showMyplan: false,
        myplanInfo: '',
        time: {},//当前跳动时间
        userInfo: null,//测试用户信息
      };
    },
    methods: {
      showMyplanInfo(info){
        this.showMyplan = true;
        this.myplanInfo = info
      },
      changeClick({ title, paneKey, disabled }) {
        // console.log(title,paneKey,disabled)
      },
      //切换服务
      router() {
        this.$router.push({ path: '/test' });
      },
      //选择项目
      clickTab(tab, index) {
        let object = document.getElementsByClassName('nut-tabs__titles-item');
        // console.log(object);
        for (let index = 0; index < object.length; index++) {
          // console.log(object[index]);
          object[index].className = 'nut-tabs__titles-item';
        }
        this.tab1value = index * 1;
        // console.log(this.tab1value)
        // document.getElementsByClassName('nut-tabs__titles-item')
        // forEach(item=>{
        //   item.className = 'nut-tabs__titles-item'
        // })
        // console.log('3')
        document.getElementById(tab).className = 'nut-tabs__titles-item nut-tabs__titles-item-check';
        // console.log(arguments)
      },
      openCheckTest(item) {
        console.log(item);
        console.log('item');
        this.showCheck = true;
        this.checkItem = item;
      },
      onCheckClose() {
        this.showCheck = false;
      },
      canelCheck() {
        this.showCheck = false;
      },
      //确认申请
      async confireCheck() {
        const userStore = await useUserStore()
        // console.log('userStore.getUserInfo',userStore.getUserInfo)
        // console.log('userStore.getUserInfo',userStore.getUserInfo[userStore.getUserType].category)
        // return
        const res = await pushOrderTest(this.checkItem.id,userStore.getUserInfo[userStore.getUserType].category,userStore.getUserInfo[userStore.getUserType].year)
        console.log(res)
        if(200 == res.response._value.code){
          Notify({ type: 'success',background: '#1989fa', duration: 2500, message: `${res.response._value.msg}` });
          //删除网页缓存
          // this.checkItem.cx = res.response._value.extend.cx
          this.myPlan.push(this.checkItem);
          for (let i = 0; i < this.allPlan.length; i++) {
            if(this.allPlan[i].place == this.checkItem.place && this.allPlan[i].type == this.checkItem.type){
              this.allPlan.splice(i,1);
              i--;
            }
          }
          //删除本地缓存
          let data = JSON.parse(localStorage.getItem('planData'))
          console.log('stringify',data)
          if(undefined == data.extend.my) data.extend.my = []
          if(undefined == data.extend.avaliable) data.extend.avaliable = []
          data.extend.my = [...this.myPlan]
          data.extend.avaliable = [...this.allPlan]
          console.log('stringify',data)
          localStorage.setItem('planData',JSON.stringify(data))
          this.showCheck = false
          // Toast.success(res.response._value.msg)
        }else {
          Notify({ type: 'danger',background: '#ee0a24', message: `${res.response._value.msg}` });
          // Toast.error(res.response._value.msg)
        }
      },
      pushReLoadPlan(){
        this.throttle();
      },
      rebackTest(item) {
        let that = this;
        if(item.cx==0){
          Notify({ type: 'danger',background: '#ee0a24', message: `当前不允许撤销，需要撤回请联系老师` });
          return
        }
        Dialog.confirm({
          title: '提示',
          message: '确认撤回本次预约？',
        }).then(async () => {
          const userStore = await useUserStore();
          console.log(item)
          let res = await rebackFreeTest(item.id);
          console.log(res)
          if(200 == res.response._value.code){
            Notify({ type: 'success',background: '#1989fa', message: `${res.response._value.msg}` });
            localStorage.removeItem('planDate');
            // setTimeout(()=>that.throttle(true),500);
            that.throttle(true);
          }else {
            Notify({ type: 'danger',background: '#ee0a24', message: `${res.response._value.msg}` });
            // Toast.error(res.response._value.msg)
          }
          // on close
        }).catch(() => {
          Notify({ type: 'success',background: '#1989fa', message: `${res.response._value.msg}` });
          // on cancel
        });

      },
      //重新渲染
      async reLoadPlan(){
        this.allPlan = []
        this.myPlan = []

        //请求数据，小于多少秒走缓存
        let data = null;
        if(localStorage.getItem('planDate')){
          const nowTime = (new Date()).getTime();
          const oldTime = localStorage.getItem('planDate')


          // 搜先显示缓存，保证用户体验
          //预约安排
          data = JSON.parse(localStorage.getItem('planData'))
          this.allPlan = data.extend.avaliable ?? []
          console.log('搜先显示缓存，保证用户体验',this.allPlan)
          for (let item of this.allPlan){
            console.log('item',item)
            //场地
            if(item.place == 1) {
              item.backSrc = 'eyesight.png'
              // item.place = '室内测试场地';
            } else if(item.place == 2) {
              item.backSrc = 'run_test.png'
              // item.place = '室外测试场地';
            }else {
              item.backSrc = 'synth.png'
              // item.place = '体测场地';
            }
          }
          //我的测试
          this.myPlan = data.extend.my ?? []
          for (let item of this.myPlan){
            //场地
            if(item.place == 1) {
              item.backSrc = 'eyesight.png'
              // item.place = '室内测试场地';
            } else if(item.place == 2) {
              item.backSrc = 'run_test.png'
              // item.place = '室外测试场地';
            }else {
              item.backSrc = 'synth.png'
              // item.place = '体测场地';
            }
          }

          //todo 数据缓存时间
          if(nowTime - oldTime < 1000*120){ //缓存命中
            Notify({
              message: '缓存读取中...', type: 'primary',
              background: '#1989fa', duration: 1000,
            });
            return
            // data = JSON.parse(localStorage.getItem('planData'))
          }else {//缓存超时
            Notify({
              message: '加载中...', type: 'primary',
              background: '#1989fa', duration: 1000,
            });
            const res = await getOrderTest();
            if(res.response._value.code != 200){
              Notify({ type: 'danger',background: '#ee0a24',duration: 1000, message: '服务器忙，请1分钟后再试'});
              return
            }
            localStorage.setItem('planData',JSON.stringify(res.response._value))
            console.log('res.response._value',res.response._value.toString())
            localStorage.setItem('planDate',(new Date()).getTime())
            data = res.response._value
          }
        }else {//缓存不存在
          Notify({
            message: '加载中...', type: 'primary',
            background: '#1989fa', duration: 1000,
          });
          const res = await getOrderTest();
          if(res.response._value.code != 200){
            Notify({ type: 'danger',background: '#ee0a24',duration: 1000, message: '服务器忙，请1分钟后再试'});
            return
          }
          localStorage.setItem('planData',JSON.stringify(res.response._value))
          console.log('res.response._value',res)
          localStorage.setItem('planDate',(new Date()).getTime())
          data = res.response._value
        }
        console.log(data)
        if(200 == data.code){
          // this.allPlan.push(...data.extend.avaliable)
          //预约安排
          this.allPlan = data.extend.avaliable ?? []
          console.log(this.allPlan)
          for (let item of this.allPlan){
            console.log('item',item)
            //场地
            if(item.place == 1) {
              item.backSrc = './eyesight.png'
              // item.place = '室内测试场地';
            } else if(item.place == 2) {
              item.backSrc = './run_test.png'
              // item.place = '室外测试场地';
            }else {
              item.backSrc = './synth.png'
              // item.place = '体测场地';
            }
          }
          //我的测试
          this.myPlan = data.extend.my ?? []
          for (let item of this.myPlan){
            //场地
            if(item.place == 1) {
              item.backSrc = './eyesight.png'
              // item.place = '室内测试场地';
            } else if(item.place == 2) {
              item.backSrc = './run_test.png'
              // item.place = '室外测试场地';
            }else {
              item.backSrc = './synth.png'
              // item.place = '体测场地';
            }
          }
          console.log(this.allPlan)
        }else {
          console.log('#######',data)
          Notify({ type: 'danger',background: '#ee0a24',duration: 1000, message: '服务器忙，请1分钟后再试'});
        }
        // console.log('res',res)
      }
    },
    async created(){
      // this.reLoadPlan();
      // 节流
      this.throttle = ((func, wait)=>{
        var timeout = null;
        var previous = 0;
        var frstPost = true;
        var waitTime = wait;
        return function(flag) {
          let context = this;
          let args = arguments;
          if (!timeout || flag == true) {
            func.apply(context, args)
            if(frstPost && localStorage.getItem('planDate')){
              timeout = new Date( 1.0*(localStorage.getItem('planDate')));
              let nowTime = new Date()
              setTimeout(function(){
                timeout = null;
              }, (waitTime - nowTime.getTime() + 1.0*(localStorage.getItem('planDate'))));
              console.log('parseInt')
              console.log(waitTime - nowTime.getTime() + 1.0*(localStorage.getItem('planDate')));
              frstPost = !frstPost;
            }else {
              timeout = new Date()
              setTimeout(function(){
                timeout = null;
              }, wait);
            }
          }else {
            let nowTime = new Date()
            console.log(waitTime)
            console.log(nowTime.toString())
            console.log(timeout)
            Notify({ type: 'danger',background: '#ee0a24',duration: 1000, message: `请勿频繁请求，${parseInt((waitTime - nowTime.getTime() + timeout.getTime())/1000)}秒之后再请求` });
            // Toast.fail("请勿频繁请求")
          }
        }
      })(this.reLoadPlan,120*1000);//todo 数据缓存时间

      this.throttle();

      const time = new Date();
      this.time.year = time.getFullYear();
      this.time.moth = time.getMonth();
      this.time.day = time.getDay();
      this.time.hour = time.getHours();
      this.time.min = time.getMinutes();
      this.time.second = time.getSeconds();
      this.time.mill = time.getMilliseconds();

      const userStore = await useUserStore()
      this.userInfo = userStore.getUserInfo.stud;


      setInterval(()=>{
        const time = new Date();
        this.time.year = time.getFullYear();
        this.time.moth = time.getMonth();
        this.time.day = time.getDate();
        this.time.hour = time.getHours();
        this.time.min = time.getMinutes();
        this.time.second = time.getSeconds();
        this.time.mill = time.getMilliseconds();
      },100)


      console.log('###userinfo',this.userInfo)
    }


  };
</script>
<style lang="scss" scoped>
.empty-image-box{
  width: 100%;
  height: 50vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.empty-image{
  width: 70%;
}
.empty-text{
  font-weight: inherit;
  font-size: inherit;
  font-family: "微软雅黑 Light";
  margin-top: 30px;
}
  .title {
    margin: auto 10px 20px 10px;
    font-weight: bold;
    width: calc(100% - 20px) ;
    font-size: large;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .title-text{
    line-height: 35px;
    height: 35px;
  }
  .replay-icon{

  }
  ::v-deep .nut-tabs__titles {
    padding: 0;
    height: 90px !important;
    border-radius: 20px;
    overflow: hidden;
  }
  .nut-tabs__titles-item {
    height: 90px !important;
  }
  .nut-tabs__titles-item-check {
    height: 90px !important;
    color: white !important;
    background-color: #007aea !important;
  }
  .tab-item {
    padding: 20px;
    font-size: large;
    line-height: 50px;
  }
  .nut-tabpane {
    padding-left: 0;
    padding-right: 0;
  }
  .test-project {
    min-height: 260px;
    background-size: 100% 100%;
    margin: 0px 0 15px 0;
    position: relative;
    padding: 20px 5px 40px 20px;
  }
  .project-item {
    position: relative;
    color: white;
    font-size: larger;
    //font-weight: bold;
    line-height: 35px;
    margin: 4px;
    //margin-left: 30px;
  }
  .project-key1 {
    height: 35px;
    font-weight: 400;
    font-size: small;
  }
  .project-key2{
    margin-top: 10px;
  }
  .project-key31{
    position: absolute;
    padding-left: 40px;
    bottom: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .project-key31 img {
    position: absolute;
    left: 0px;
    margin-right: 15px;
    height: 26px;
    padding-bottom: 3px;
  }
  .project-key3 {
    position: absolute;
    padding-left: 40px;
    bottom: 40px;
    width: 85%;
  }
  .project-key3>*{
  }
  .project-key3 img {
    position: absolute;
    left: 0px;
    margin-right: 10px;
    height: 30px;
    padding-left: 0.5px;
  }
  .place-desc{
    //position: relative;
    width: 70vw;
    overflow: hidden;
    text-overflow: ellipsis;
    float: left;
    white-space:nowrap;
  }
  .item-desc{
    width: 68%;
    overflow: hidden;
    text-overflow: ellipsis;
    float: left;
    white-space:nowrap;
  }
  .people-num{
    float: right;
    margin-right: 5px;
    white-space:nowrap;
    font-size: x-large;
  }
  .people-reback{
    float: right;
    margin-top: 3px;
    margin-right: 10px;
    white-space:nowrap;
    font-size: large;
  }
  //确认弹窗
  .check-title {
    text-align: center;
    margin: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-right: 20px;
  }
  :deep .nutui-popup__close-icon--top-right {
    top: 40px;
    right: 4vw;
  }
  .cell-box {
    margin: -15px 40px 0 40px;
    //padding: 20px;
  }
  .info-item {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .info-item * {
    // display: inline;
  }
  .info-item .key {
    //min-width: 200px;
    text-align-last: justify;
    min-width: 180px;
    //font-size: large;
    margin-right: 15px;
    //font-weight: bold;
    //display: block;
  }
  .info-item .value {
    display: inline;
  }
  :deep .nut-cell__title {
    display: inherit;
    width: 200px;
  }
  :deep .nut-cell,
  :deep .nut-cell__value {
    font-size: inherit;
  }
  .check-button {
    height: 80px;
    margin: 60px 40px 30px 40px;
    display: flex;
    justify-content: space-between;
  }
  :deep .nut-button {
    height: 80px;
    width: 300px;
    font-size: large;
    border-radius: 40px;
  }
  .nut-divider{
    --van-divider-margin: 5px;
    --van-padding-md: 5px;
    --van-divider-content-padding: 5px;
    --van-divider-line-height: 6px;
  }
  .nut-divider-hairline{
    --van-divider-margin: 5px;
    --van-padding-md: 5px;
    --van-divider-content-padding: 5px;
    --van-divider-line-height: 6px;
  }
  .divider-xian{
    width: 100%;
    margin: 15px auto;
    height: 1px;
    background-color: #c2c2c2;
  }
  .user-detail{
    border-radius: 30px;
    overflow: hidden;
    //background-color: #eeeeee;
    //padding: 20px;
    margin-top: -30px;
    margin-bottom: 20px;
    font-size: larger;

    //display: flex;
    //justify-content: space-between;
    //align-items: center;
  }
  .user-info{
    color: #1a1a1a;
    //width: 50%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

</style>
